package auth

// 用来生成临时令牌的token

import (
	"context"
	"git.mycaigou.com/gfyx/common/cache"
	"github.com/google/uuid"
)

type TempToken struct {
	ctx         context.Context
	redisClient *cache.TRedis
	keyPrefix   string
	expireTime  int
}

func NewTempToken(ctx context.Context) TempTokenIface {
	redisClient, _ := cache.TenantRedis()
	return &TempToken{
		ctx:         ctx,
		redisClient: redisClient,
		keyPrefix:   "common:temp-token:",
		expireTime:  600,
	}
}

func (t *TempToken) Get(id string) (string, error) {
	cacheKey := t.keyPrefix + id
	token := uuid.New().String()
	// 10 分钟有效
	_, err := t.redisClient.Set(t.ctx, cacheKey, token, true, t.expireTime)
	if err != nil {
		return "", err
	}
	return token, nil
}

func (t *TempToken) Verify(id, token string, clear bool) (bool, error) {
	cacheKey := t.keyPrefix + id
	cacheToken, err := t.redisClient.Get(t.ctx, cacheKey)
	if err != nil {
		return false, err
	}
	if cacheToken != token {
		return false, nil
	}
	if clear {
		_, err = t.redisClient.Del(t.ctx, cacheKey)
		if err != nil {
			return false, err
		}
	}
	return true, nil
}
